{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Summary\n",
    "In this notebook we will setup a *TSEB* model to run a time series data at point scale.\n",
    "\n",
    "# TSEB setup\n",
    "The main input data consists on an ASCII table with tab separators and with the first row containing the names of the variables. The table should at least contain the following field names (case sensitive):\n",
    ">* **TSEB-PT** : `Year, DOY, Time, Trad, VZA, Ta, u, ea, Sdn, LAI & hc`\n",
    ">* **DTD** : `Year, DOY, Time, Trad_0, Trad, VZA, Ta_0, Ta, u, ea, Sdn, LAI & hc`\n",
    ">* **TSEB-2T** : `Year, DOY, Time, Tc, Ts, Ta, u, ea, Sdn, LAI & hc`\n",
    "\n",
    "**Year** is not really used in the model but is kept in case several years were processed, **DOY** is the day of the year (1-366), **Time** is the local-solar measurement time in decimal hours (0-24). **Trad** is the radiometric composite temperature; **Trad_0**, the same for time 0 (close to sunrise) for *DTD* model; **Ts** and **Tc** are the component soil and canopy temperatures for *TSEB-2T*; **Ta** is the air temperature: all temperatures expressed in Kelvin. **u** is the wind speed measurement (m s$^{-1}$), **ea** is the atmospheric vapour pressure (mb), **Sdn** is the shortwave irradiance (W m$^{-2}$), **LAI** is the effective leaf area index, and **hc** is the canopy height (m).\n",
    "\n",
    "Additional input variables that can be included in the table are: **SAA** solar azimuth angle, **SZA** solar zenith angle, **Ldn** incoming longwave radiation (W m$^{-2}$), **fc** vegetation fractional cover, **fg** vegetation green fraction, **wc** canopy width-to-height ratio, and **G** soil heat flux (W m$^{-2}$).\n",
    "\n",
    "If any of those additional variables are not found in the table they will be internally estimated by TSEB (in case of **SAA**, **SZA**, **Ldn**, **fc**, and **G**) or default values will be used (in case of other variables). The order of the columns is not relevant, and neither whether there are additional columns in the table (they will be ignored if their names do not match any of the possible input variables).\n",
    "\n",
    "For more information about the inputs and outputs of pyTSEB click [here](./README_Notebooks.md \"README_Notebooks.md\")\n",
    "\n",
    "## Select the input and output files and fill the information in all tabs \n",
    "You can press the *Load Configuration File* button to load a configuration text file which will upload all its information to the corresponding cells. \n",
    "\n",
    "You can also press the *Save Configuration File* button to save the configuration in a text file which can be used in future runs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from pyTSEB.TSEBIPythonInterface import TSEBIPythonInterface # import the PyTSEB class object in the pyTSEB.py module\n",
    "setup = TSEBIPythonInterface() # Create the setup instance from the PyTSEB class object\n",
    "setup.point_time_series_widget() # Load the TSEB configuration Widget"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Run TSEB\n",
    "Once TSEB is configured we parsed all the information in the widgets and run the selected model. \n",
    "\n",
    "After the processing is done an ASCII table with the following variables will be written in the output txt file:\n",
    ">Year, DOY, Time, LAI, f_g, skyl, VZA, SZA, SAA, Ldn, Rn_model, Rn_sw_veg, Rn_sw_soil, Rn_lw_veg, Rn_lw_soil, Tc, Ts, Tac, LE_model, H_model, LE_c, H_c, LE_s, H_s, flag, zo, d, G_model, R_s, R_x, R_a, u_friction, L, n_iterations\n",
    "\n",
    "where variables with the same name as input variables have the same meaning, and for the others: *skyl* is the ratio of diffuse radiation, *Rn_model* is net radiation (W m-2; *sw* and *lw* subscripts stand for shortwave and longwave, *veg* and *soil* for canopy and soil), *Tc*, *Ts* and *Tac* are canopy, soil and inter-canopy-air temperatures (K), *LE_model* is latent heat flux and *H_model* is sensible heat flux (W m-2; subscripts *c* and *s* stand for canopy and soil respectively), *flag* is a quality flag (255==BAD), *zo* and *d* are roughness length and zero-plane displacement height (m), *R_s*, *R_x* and *R_a* are resistances to heat and momentum transport (s m-1), *u_friction* is friction velocity (m s-1), *L* is the Monin-Obukhov length (m) and *n_iterations* is the number of iterations of TSEB needed to achieve model convergence.\n",
    "\n",
    "# Display results\n",
    "Now we can open the output and plot the TSEB outputs:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from bokeh.plotting import figure, output_file, show\n",
    "from bokeh.io import output_notebook\n",
    "from bokeh.models import *\n",
    "from bokeh.resources import INLINE\n",
    "output_notebook(resources=INLINE)\n",
    "# get the data\n",
    "output=np.genfromtxt(setup.outputFile,names=True,dtype=None)\n",
    "# create a datetime variable\n",
    "timestamp=np.array(output['Year'].astype(int).astype(str),dtype='datetime64')\n",
    "timestamp=timestamp+np.array(output['DOY'],dtype='timedelta64[D]')\n",
    "timestamp=np.array(timestamp.astype(str))\n",
    "# Add time to the time\n",
    "for i,string in enumerate(timestamp):\n",
    "    timestamp[i]=string+'T00:00'\n",
    "timestamp=np.array(timestamp,dtype='datetime64')\n",
    "delta=np.array(output['Time'].astype(int),dtype='timedelta64[h]')\n",
    "timestamp=timestamp+delta\n",
    "timestamp=timestamp+np.array(np.array((output['Time']-output['Time'].astype(int))*60,dtype='timedelta64[m]'))\n",
    "\n",
    "# Create  Figure \n",
    "source=ColumnDataSource(data=dict(timestamp=timestamp,Year=output['Year'],DOY=output['DOY'],Time=np.round(output['Time'],2),\n",
    "                                  H=np.round(output['H_model'],0),LE=np.round(output['LE_model'],0),Rn=np.round(output['Rn_model'],0),\n",
    "                                  G=np.round(output['G_model'],0),flag=output['flag']))\n",
    "p = figure(title=\"Time Series\", plot_width=600, plot_height=400,x_axis_type=\"datetime\")\n",
    "# Plot all the points as dashed lines\n",
    "p.line('timestamp','H',source=source, color='red',line_dash=[4,4])\n",
    "p.line('timestamp','LE',source=source, color='blue', line_dash=[4,4])\n",
    "line=p.line('timestamp','Rn',source=source, color='black', line_dash=[4,4])\n",
    "p.line('timestamp','G',source=source, color='green', line_dash=[4,4])\n",
    "# Create a hover tool\n",
    "hover = HoverTool(tooltips=[(\"Date\", \"@Year\"),('DOY',\"@DOY\"),\n",
    "                           ('Time',\"@Time\"),('H','@H'),\n",
    "                           ('LE','@LE'),('Rn','@Rn'),\n",
    "                            ('G','@G'),('flag','@flag')],line_policy='nearest',point_policy='snap_to_data',mode='vline', renderers=[line])\n",
    "p.add_tools(hover)\n",
    "# Filter only good quatlity data points flag<5:\n",
    "H=np.array(output['H_model'])\n",
    "H[output['flag']>=5]=float('nan')\n",
    "LE=np.array(output['LE_model'])\n",
    "LE[output['flag']>=5]=float('nan')\n",
    "Rn=np.array(output['Rn_model'])\n",
    "Rn[output['flag']>=5]=float('nan')\n",
    "G=np.array(output['G_model'])\n",
    "G[output['flag']>=5]=float('nan')\n",
    "#Plot good quality data as straight lines\n",
    "p.line(x=timestamp,y=H, color='red', legend='H')\n",
    "p.line(x=timestamp,y=LE, color='blue', legend='LE')\n",
    "p.line(x=timestamp,y=Rn, color='black', legend='Rn')\n",
    "p.line(x=timestamp,y=G, color='green', legend='G')\n",
    "\n",
    "show(p);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.4.3"
  },
  "widgets": {
   "state": {
    "4768dfb89d7d4862a4788ac2de0f541d": {
     "views": [
      {
       "cell_index": 1
      }
     ]
    },
    "832a1e7830a747e1b1789f8121d0efc0": {
     "views": [
      {
       "cell_index": 1
      }
     ]
    },
    "ce2f49e07fc149f1b26bf501318cd628": {
     "views": [
      {
       "cell_index": 1
      }
     ]
    }
   },
   "version": "1.2.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
